<?php

namespace library;

use app\model\PhoneDn;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use support\Log;
use support\Redis;

class youyin
{
    private string $token;

    public function __construct()
    {

        if (empty(Redis::get('youyin_token'))){
            $this->token = $this->getToken();
            if (!empty($this->token)) {
                Redis::set('youyin_token', $this->token, 'EX',3600);
            } else {
                Log::error('Token 获取失败');
            }
        }else{
            $this->token = Redis::get('youyin_token');
        }
    }

    public function getToken(): ?string
    {
        $url = "https://xtapi.uincall.com/api/call/union400Login.action";
        $timestamp = date('YmdHis');
        $appver = 1;
        $user = env('YOUYIN_USER');
        $pwd = env('YOUYIN_PWD');

        $secret = md5('appver' . $appver . 'timestamp' . $timestamp . 'user' . $user . $pwd);

        $data = [
            'appver' => $appver,
            'timestamp' => $timestamp,
            'user' => $user,
            'secret' => $secret,
        ];

        try {
            $client = new Client(['timeout' => 10, 'verify' => false]);
            $response = $client->post($url, ['form_params' => $data]);
            $result = json_decode($response->getBody()->getContents(), true);

            if ($result && $result['errcode'] === 0) {
                return $result['data']['token'];
            } else {
                Log::error('Token 获取失败：' . json_encode($result, JSON_UNESCAPED_UNICODE));
                return null;
            }
        } catch (GuzzleException $e) {
            Log::error('Token 获取异常：' . $e->getMessage());
            return null;
        }
    }

    public function bind(string $phone, string $dn): array
    {
        $url = "https://xtapi.uincall.com/api/call/addExtensionV2.action";
        $timestamp = date('YmdHis');
        $appver = 1;
        $user = env('YOUYIN_USER');
        $account = env('YOUYIN_ACCOUNT');

        $dataList = [['dn' => $dn, 'tel' => $phone]];
        $jsonData = json_encode($dataList, JSON_UNESCAPED_UNICODE);

        $secret = md5('account' . $account . 'appver' . $appver . 'data' . $jsonData . 'timestamp' . $timestamp . 'user' . $user . $this->token);

        $postData = [
            'appver' => $appver,
            'user' => $user,
            'timestamp' => $timestamp,
            'account' => $account,
            'data' => $jsonData,
            'secret' => $secret
        ];

        try {
            $client = new Client(['timeout' => 10, 'verify' => false]);
            $response = $client->post($url, ['form_params' => $postData]);
            $result = json_decode($response->getBody()->getContents(), true);
            if ($result && $result['errcode'] === 0) {
                PhoneDn::create([
                    'dn' => $dn,
                    'phone' => $phone
                ]);
                Log::info("dn: {$dn}, phone: {$phone} 绑定成功");
                return apiSuccess('绑定成功');
            } else {
                Log::info("绑定失败：" . json_encode($result, JSON_UNESCAPED_UNICODE));
                return apiError($result['errmsg'] ?? '未知错误');
            }
        } catch (GuzzleException $e) {
            Log::error("分机绑定异常：{$e->getMessage()}");
            return apiError('分机绑定异常');
        }
    }

    public function unbind(string $dn): array
    {
        $url = "https://xtapi.uincall.com/api/call/deleteExtensionV2.action";
        $timestamp = date('YmdHis');
        $appver = 1;
        $user = env('YOUYIN_USER');
        $account = env('YOUYIN_ACCOUNT');

        $secret = md5('account' . $account . 'appver' . $appver . 'dn' . $dn . 'timestamp' . $timestamp . 'user' . $user . $this->token);

        $postData = [
            'appver' => $appver,
            'user' => $user,
            'timestamp' => $timestamp,
            'account' => $account,
            'dn' => $dn,
            'secret' => $secret
        ];

        try {
            $client = new Client(['timeout' => 10, 'verify' => false]);
            $response = $client->post($url, ['form_params' => $postData]);
            $result = json_decode($response->getBody()->getContents(), true);

            if ($result && $result['errcode'] === 0) {
                $phone = PhoneDn::where('dn',$dn)->value('phone');
                if ($phone) {
                    PhoneDn::where('dn',$dn)->delete();
                }
                Log::info("dn{$dn} phone{$phone} 解绑成功");
                return apiSuccess("解绑成功");
            } else {
                Log::info("解绑失败：" . json_encode($result, JSON_UNESCAPED_UNICODE));
                return apiError($result['errmsg'] ?? '未知错误');
            }
        } catch (GuzzleException $e) {
            Log::error("解绑接口异常：{$e->getMessage()}");
            return apiError('解绑接口异常');
        }
    }


    //分机查询
    public function getExtension($pageNow = 1, $pageSize = 10): array
    {
        // 请求的 URL
        $url = "https://xtapi.uincall.com/api/call/batchQueryExtensionV2.action";
        $timestamp = date('YmdHis');
        $appver = 1;
        $user = env('YOUYIN_USER');
        $account = env('YOUYIN_ACCOUNT');

        $secret = md5(
            'account' . $account .
            'appver' . $appver .
            'pageNow' . $pageNow .
            'pageSize' . $pageSize .
            'timestamp' . $timestamp .
            'user' . $user
            . $this->token);

        $postData = [
            'appver' => $appver,
            'user' => $user,
            'timestamp' => $timestamp,
            'account' => $account,
            'secret' => $secret,
            'pageNow' => $pageNow,
            'pageSize' => $pageSize
        ];

        try {
            $client = new Client(['timeout' => 10, 'verify' => false]);
            $response = $client->post($url, ['form_params' => $postData]);
            $result = json_decode($response->getBody()->getContents(), true);

            if ($result && $result['errcode'] === 0) {
                return apiSuccess($result['data']);
            } else {
                Log::info("分机查询失败：" . json_encode($result, JSON_UNESCAPED_UNICODE));
                return apiError($result['errmsg'] ?? '未知错误');
            }
        } catch (GuzzleException $e) {
            Log::error("分机查询接口异常：{$e->getMessage()}");
            return apiError('分机查询接口异常');
        }


    }


    //清空分机号
    public function clearExtension(): array
    {
        // 请求的 URL
        $url = "https://xtapi.uincall.com/api/call/clearExtensionV2.action";
        $timestamp = date('YmdHis');
        $appver = 1;
        $user = env('YOUYIN_USER');
        $account = env('YOUYIN_ACCOUNT');

        $secret = md5(
            'account' . $account .
            'appver' . $appver .
            'timestamp' . $timestamp .
            'user' . $user
            . $this->token
        );

        $postData = [
            'appver' => $appver,
            'user' => $user,
            'timestamp' => $timestamp,
            'account' => $account,
            'secret' => $secret
        ];
        try {
            $client = new Client(['timeout' => 10, 'verify' => false]);
            $response = $client->post($url, ['form_params' => $postData]);
            $result = json_decode($response->getBody()->getContents(), true);

            if ($result && $result['errcode'] === 0) {
                return apiSuccess($result['data']);
            } else {
                Log::info("清空分机号失败：" . json_encode($result, JSON_UNESCAPED_UNICODE));
                return apiError($result['errmsg'] ?? '未知错误');
            }
        } catch (GuzzleException $e) {
            Log::error("清空分机号接口异常：{$e->getMessage()}");
            return apiError('清空分机号接口异常');

        }
    }

    //http://btmztlzrk1.wcnm.gnncdn.ciyuanmi.top
    //.
    //OK-dwFW89GFhZHa

    //通话结束回调
    public function callEnd($callId = ''): array
    {
        return apiSuccess();
    }



}
